<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="payment_name">
        <el-input
          v-model="queryParams.payment_name"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['member:payment:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['member:payment:change']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['member:payment:del']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <h4>微信官方支付请登录微信支付商户平台=》产品中心=》开发配置！进行配置</h4>
    <h3>
      支付授权目录：<span>{{ payPath }}</span>

      <el-button
        style="margin-left: 30px"
        type="primary"
        id="copy"
        :data-clipboard-text="payPath"
        @click="copy"
        >复制</el-button
      >
    </h3>
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="payment_name" />
      <el-table-column label="编码" align="center" prop="payment_code" />
      <el-table-column label="费率%" align="center" prop="pay_rate" />
      <el-table-column label="回调地址" align="center" prop="callback_url" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <!-- <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          /> -->
          <el-tag type="success" v-if="scope.row.status == 1">启用</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="默认支付" align="center" prop="is_default">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.is_default == 1">是</el-tag>
          <el-tag type="warning" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="created_at"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['member:payment:change']"
            >修改</el-button
          >
          <el-button
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['member:payment:del']"
            >删除</el-button
          >
          <!--  v-hasPermi="['api:v1:delMpPayment']" -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form1" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="payment_name">
          <el-input v-model="form.payment_name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="费率%" prop="pay_rate">
          <el-input placeholder="请输入费率" v-model="form.pay_rate">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="默认支付" prop="is_default">
          <el-radio-group v-model="form.is_default">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模板" prop="payment_code">
          <el-select
            v-model="form.payment_code"
            placeholder="请选择模板"
            filterable
            @change="handlePaymentChange"
          >
            <el-option
              v-for="payment in paymentTemplateList"
              :key="payment.code"
              :label="payment.name"
              :value="payment.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in currentPaymentSetting"
          :key="index"
          :label="item.label"
          :prop="item.name"
        >
          <ImageUpload
            :extraData="{ type: item.name }"
            :limit="1"
            :uploadImgUrl="uploadFileUrl"
            v-if="item.type == 'file'"
            :fileType="['pem']"
            v-model:value="item.val"
            @input="uploadSuccess($event, item)"
          />
          <!--   v-model="item.val" -->
          <el-input
            v-else
            :placeholder="item.placeholder"
            v-model="item.val"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMpPayment,
  addMpPayment,
  updateMpPayment,
  getMpPayment,
  delMpPayment,
  getMpPaymentTemplateList,
} from "@/api/member/paySet";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "mpPay",
  components: { ImageUpload },
  data() {
    return {
      payPath: "",
      uploadFileUrl:
        import.meta.env.VITE_APP_ENV == "development"
          ? import.meta.env.VITE_APP_BASE_API + "/member/payment/uploadPayfile"
          : window.location.origin + "/member/payment/uploadPayfile",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      paymentTemplateList: [],
      currentPaymentSetting: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      template_file: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        payment_name: undefined,
        payment_code: undefined,
        is_default: undefined,
        status: undefined,
      },
      currentPaymentFilePath: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        payment_name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        pay_rate: [
          { required: true, message: "请填写手续费率", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        payment_code: [
          { required: true, message: "请选择模板", trigger: "blur" },
        ],
      },
      settingRules: {},
      c: "",
    };
  },
  created() {
    console.log(this.Clipboard);
    this.getList();
  },
  methods: {
    copy() {
      let c = new this.Clipboard("#copy");
      this.c = c;
      c.on("success", () => {
        this.$message.success("复制成功");
        console.log(c);
        this.c.destory();
      });
      c.on("error", () => {
        this.$message.error("复制失败");
        this.c.destory();
      });
    },
    uploadSuccess(res, item) {
      console.log("imgsucces2222s", res);
      if (res.code == 200) {
        this.$message.success("文件上传成功,该文件不支持预览");
        item.val = res.data;
        console.log(item, this.paymentTemplateList, this.currentPaymentSetting);
      }
      //   return false;
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      listMpPayment(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log("response", response);
          this.dataList = response.data.items;
          this.total = response.total;
          this.loading = false;
          this.payPath = response.data.payPath;
        }
      );
    },
    getPaymentTemplateList() {
      this.loading = true;
      getMpPaymentTemplateList({}).then((response) => {
        this.paymentTemplateList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.currentPaymentSetting = [];
      this.form = {
        id: undefined,
        payment_name: undefined,
        payment_code: undefined,
        setting: undefined,
        callback_url: undefined,
        is_default: 0,
        status: 1,
        pay_rate: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加渠道";
      this.getPaymentTemplateList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMpPayment(id).then((response) => {
        this.form = response.data;
        this.currentPaymentSetting = this.form.setting;
        this.open = true;
        this.title = "修改配置";
        this.getPaymentTemplateList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("submitForm", this.currentPaymentFilePath);
      this.form.setting = this.currentPaymentSetting;
      // 写入temp_file
      this.form.file_path = this.template_file;
      if (this.form.id != undefined) {
        updateMpPayment(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addMpPayment(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
      // this.$refs.form1.validate((valid) => {
      //   console.log("valid", valid);
      //   if (valid) {
      //     this.form.setting = this.currentPaymentSetting;
      //     // 写入temp_file
      //     this.form.file_path = this.currentPaymentFilePath.template_file;
      //     if (this.form.id != undefined) {
      //       updateMpPayment(this.form).then((response) => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addMpPayment(this.form).then((response) => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   } else {
      //     console.log("11111");
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？')
        .then(function () {
          return delMpPayment(dictIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handlePaymentChange(code) {
      if (code) {
        this.template_file =
          this.paymentTemplateList[code].template_file ||
          this.paymentTemplateList[code].code;
        console.log(this.template_file);
        this.currentPaymentSetting = this.paymentTemplateList[code]
          ? this.paymentTemplateList[code].setting
          : [];
      }
    },
  },
};
</script>
